



<template>
  <div>
    <div class="btn-box">
      <!-- v-if="(!quality.status || quality.status=='0' || quality.status=='3') && checkPermission(['WORK_REPORT_MANAGER','WORK_REPORT_ACCEPTER','合同报工员'])" -->
      <ht-upload
        v-if="quality.id && (quality.status != '2' || checkPermission(['WORK_REPORT_MANAGER']))"
        ref="myUpload"
        class="upload-demo"
        dbKey="Trd"
        busField="workReport"
        :busType="busType"
        :busKey="quality.id + ''"
        ftpKey="ftp"
        v-model="fileList"
        :show-file-list="false"
        :before-upload="beforUpload"
        :on-success="afterUpload"
      >
        <a-button type="primary"> 上传 </a-button>
      </ht-upload>
      <a-button @click="handleDownload()"> 下载 </a-button>
      <a-button v-if="quality.id && quality.status != '2'" @click="removeAttachRow()"> 删除 </a-button>

      <a-button @click="downloadTemplate('2f5d25a58e094410bee9f1a9b59215a9', 'a6e7154fd81e4069a3cf809a90999ee3')">
        下载模板
      </a-button>
      <span style="font-size: 12px; color: red; padding-left: 20px; font-weight: normal">
        请下载质量通知单模板,按模板要求填写。
      </span>
    </div>
    <a-table
      :columns="columns"
      :data-source="attachs"
      :rowKey="
        (record, index) => {
          return record.id
        }
      "
      bordered
      :pagination="false"
      :row-selection="{ selectedRowKeys: selectedRowKeys, onChange: onSelectChange }"
    >
      <span slot="createTimeRender" slot-scope="text, record">
        <span v-if="record.createTime && record.createTime != '1900-01-01 00:00:00'">
          {{ record.createTime }}
        </span>
      </span>
      <span slot="previewRender" slot-scope="text, record">
        <span class="font-active" @click="handlePreview(record)">
          {{ record.fileName }}
        </span>
      </span>

      <span slot="index" slot-scope="text, record, index">
        {{ index + 1 }}
      </span>
    </a-table>
  </div>
</template>

<script>
import Vue from 'vue'
import { getAction, postAction,previewAttach } from '@/api/manage'
import { formatFileSize, endWith } from '@/utils/common.js'
import { ACCESS_TOKEN } from '@/store/mutation-types'
import '@/config/upload.install.js'
export default {
  props: {
    busType: {
      type: String,
      default: '',
    },
    busKey: {
      type: String,
      default: '',
    },
    formName: {
      type: String,
      default: '',
    },
    permission: {
      type: Array,
      default: () => {
        return []
      },
    },
    quality: {
      type: Object,
      default: () => {
        return {}
      },
    },
  },
  data() {
    return {
      userinfo: {
        info: this.$store.getters.userInfo,
        module: 'ContractReportInfo',
      },
      urls: {
        attachs: 'workReport/attach/attachList',
        editAttach: 'workReport/attach/edit',
        deleteAttach: 'workReport/attach/delete',
        myPermission: '/workReport/project/myPermission',
      },
      attachs: [],
      columns: [
        {
          title: '序号',
          scopedSlots: { customRender: 'index' },
          width: '7%',
        },
        {
          title: '文件名称',
          dataIndex: 'fileName',
          key: 'fileName',
          width: '48%',
          scopedSlots: { customRender: 'previewRender' },
        },
        {
          title: '文件大小',
          dataIndex: 'fileSize',
          key: 'fileSize',
          width: '15%',
        },
        {
          title: '上传人',
          dataIndex: 'createUser',
          key: 'createUser',
          width: '15%',
          align: 'center',
        },
        ,
        {
          title: '上传时间',
          dataIndex: 'createTime',
          key: 'createTime',
          width: '15%',
          align: 'center',
          scopedSlots: { customRender: 'createTimeRender' },
        },
      ],
      currentSelection: [],
      selectedRowKeys: [],
      fileList: [],
    }
  },
  mounted() {
    this.fetchAttach()
  },
  methods: {
    checkPermission(powers) {
      let hasPower = false
      for (let p of powers) {
        if (this.permission.indexOf(p) > -1) {
          hasPower = true
          break
        }
      }
      return hasPower
    },
    fetchAttach() {
      if (this.busType && this.busKey) {
        getAction(this.urls.attachs + '?busType=' + this.busType + '&busKey=' + encodeURIComponent(this.quality.id), {}).then((res) => {
          if (res.success) {
            this.attachs = res.result
            if (!this.attachs || this.attachs.length == 0) {
              this.attachs = []
            }
          }
        })
      }
    },
    getAttach() {
      return this.attachs
    },
    handleDownload() {
      if (this.currentSelection.length == 1) {
        let record = this.currentSelection[0]
        if (record.busFk) {
          const token = Vue.ls.get(ACCESS_TOKEN)
          window.open(
            process.env.VUE_APP_API_BASE_URL + '/workReport/attach/download?token=' + token + '&id=' + record.busFk
          )
        }
      } else if (this.currentSelection.length > 1) {
        let ids = []
        this.currentSelection.forEach((r) => {
          ids.push(r.busFk)
        })
        //申请流水号+合同名称+合同编号+申请人
        let tempFileName = this.quality.name+"#"+this.quality.contractName+"#"+this.quality.contractNo+"#"+this.quality.applyUser+".zip"
        var href =
        this.API_BASE_URL +
        '/common/downLoadBatchWithFileName?attachIds=' +
        ids.join(",") +
        '&dbKey=Trd&ftpKey=ftp&token=' +
        this.$ls.get(ACCESS_TOKEN) +
        '&zipFileName=' +
        encodeURIComponent(tempFileName)
        this.doDownLoadByIframe(href)
      }
    },
    downloadTemplate(id, tempId) {
      if (!this.quality.contractNo) {
        this.$messageWorkReport.warning('请选择所属合同')
        return
      }
      if (!this.quality.contractName) {
        this.$messageWorkReport.warning('请选择所属合同')
        return
      }
      if (!this.quality.companyName) {
        this.$messageWorkReport.warning('请选择签订公司')
        return
      }
      if (!this.quality.supplierName) {
        this.$messageWorkReport.warning('请选择供应商')
        return
      }
      let tempFileName = this.quality.qualityNo+"#"+this.quality.name+"#"+this.quality.contractNo+".zip"
      let url =
        process.env.VUE_APP_API_BASE_URL +
        '/ps/workReport/downloadQualityTemplate?id=' +
        id +
        '&tempId=' +
        tempId +
        '&contractNo=' +
        this.quality.contractNo +
        '&contractName=' +
        this.quality.contractName +
        '&companyName=' +
        this.quality.companyName +
        '&supplierName=' +
        this.quality.supplierName+
        "&zipName="+encodeURIComponent(tempFileName)
      url = url.replace('#', '@@@@')
      url = process.env.VUE_APP_API_BASE_URL + '/ps/workReport/downloadQualityTemplate'
      let param = {}
      param.id = id
      param.tempId = tempId
      param.contractNo = this.quality.contractNo
      param.contractName = this.quality.contractName
      param.companyName = this.quality.companyName
      param.supplierName = this.quality.supplierName
      param.zipName = encodeURIComponent(tempFileName)
      this.openPostWindow(url, param)
    },
    openPostWindow(url, data) {
      var tempForm = document.createElement('form')
      tempForm.id = 'tempForm1'
      tempForm.method = 'post'
      tempForm.action = url
      tempForm.target = '_blank' //打开新页面
      tempForm.enctype = 'application/json'
      for (let k in data) {
        var hideInput = document.createElement('input')
        hideInput.type = 'hidden'
        hideInput.name = k //后台要接受这个参数来取值
        hideInput.value = data[k] //后台实际取到的值
        tempForm.appendChild(hideInput)
      }
      if (document.all) {
        tempForm.attachEvent('onsubmit', function () {}) //IE
      } else {
        var subObj = tempForm.addEventListener('submit', function () {}, false) //firefox
      }
      document.body.appendChild(tempForm)
      if (document.all) {
        tempForm.fireEvent('onsubmit')
      } else {
        tempForm.dispatchEvent(new Event('submit'))
      }
      tempForm.submit()
      document.body.removeChild(tempForm)
    },
    beforUpload() {
      if (this.currentSelection.length > 1) {
        this.$messageWorkReport.warning('请选择一条记录上传')
        return false
      }
      return true
    },
    afterUpload(response) {
      let record = {}
      // if (this.currentSelection.length == 1) {
      //   record = this.currentSelection[0]
      // }
      if (response && response.length > 0) {
        this.$set(record, 'formName', this.formName)
        this.$set(record, 'fileName', response[0].fileName)
        this.$set(record, 'filePath', response[0].path)
        this.$set(record, 'fileSize', response[0].size)
        this.$set(record, 'createUser', response[0].uploaderName)
        this.$set(record, 'createUserId', response[0].uploader)
        this.$set(record, 'createTime', response[0].uploadTime)
        this.$set(record, 'busType', response[0].busType)
        this.$set(record, 'busKey', response[0].busKey)
        this.$set(record, 'busFk', response[0].id)
        this.$set(record, 'platForm', 'HTE')
        postAction(this.urls.editAttach, record).then((res) => {
          if (res.success) {
            this.fetchAttach()
          } else {
            this.$messageWorkReport.error(res.message)
          }
        })
      }
    },
    onSelectChange(selectedRowKeys, selectedRows) {
      this.selectedRowKeys = selectedRowKeys
      this.currentSelection = selectedRows
    },
    removeAttachRow() {
      let record = this.currentSelection[0]
      if (!this.checkPermission(['WORK_REPORT_MANAGER'])) {
        if (record.createUserId != this.userinfo.info.username) {
          return this.$messageWorkReport.warning('请勿删除非本人上传的文件')
        }
        // if (record.formName != this.formName) {
        //   if (record.createUserId != this.userinfo.info.username) {
        //     return this.$messageWorkReport.warning('请勿删除非本节点上传的文件')
        //   }
        // }
      }
      if (record.id) {
        postAction(this.urls.deleteAttach + '/' + record.id, {}).then((res) => {
          if (res.success) {
            this.fetchAttach()
          } else {
            this.$messageWorkReport.error(res.message)
          }
        })
      }
    },
    handlePreview(file) {
      let that = this
      if (
        endWith(file.fileName, 'rar') ||
        endWith(file.fileName, 'zip') ||
        endWith(file.fileName, 'dwg') ||
        endWith(file.fileName, 'tgz')
      ) {
        return true
      }

      let params={
        id:file.busFk,
        ftpKey:'ftp'
      };
      previewAttach(params).then(result=>{
        const url=URL.createObjectURL(result)
        window.open(process.env.BASE_URL+'/pdf/web/viewer.html?file=' + url)
      }).catch(err => {
        this.$messageWorkReport.warning('下载文件失败');
      })
    },
    doDownLoadByIframe(url) {
      if (document.getElementById('_attachToolView_downloadfile_frame') == null) {
        var downloadFrame = $('<iframe id="_attachToolView_downloadfile_frame" style="display: none"></iframe>')
        downloadFrame.appendTo($('body'))
      }
      var iframe = document.getElementById('_attachToolView_downloadfile_frame')
      iframe.src = url
    },
  },
  watch: {
    busType(newV, oldV) {
      this.fetchAttach()
    },
    busKey(newV, oldV) {
      this.fetchAttach()
    },
  },
}
</script>

<style lang="less" scoped>
/deep/ .upload-demo {
  display: inline-block;
}
/deep/.ant-col .ant-form-item-label {
  min-width: 135px;
  line-height: 40px;
  display: inline-block;
  overflow: hidden;
  line-height: 39.9999px;
  white-space: nowrap;
  text-align: right;
  vertical-align: middle;
}
/deep/.ant-row .ant-form-item {
  display: flex;
}
/deep/.ant-col .ant-form-item-control-wrapper {
  width: 100%;
}
/deep/.anticon .anticon-plus-circle {
  display: flex;
  align-items: center;
}
/deep/.ant-calendar-picker {
  width: 100%;
}
.btn-box {
  margin-bottom: 15px;
  .ant-btn {
    margin-right: 10px;
  }
}
.font-active {
  color: #249af4;
}
</style>  